package com.xiaofan.config;

import com.xiaofan.bean.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *自定义认证器
 * @author 晓帆
 * @version 1.0
 **/
public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        Collection<Realm> realms = this.getRealms();
        MallToken token = (MallToken) authenticationToken;
        String type = token.getType();
        List<Realm> realmsList = new ArrayList<>();
        //判断是哪个请求并且分发请求，type中
        for (Realm realm : realms) {
            if (realm.getName().toLowerCase().contains(type)){
                realmsList.add(realm);
            }
        }
        return realmsList.size() == 1 ? this.doSingleRealmAuthentication((Realm)realmsList.iterator().next(), authenticationToken) :
                this.doMultiRealmAuthentication(realmsList, authenticationToken);

    }
}
